package com.lzw.cpvideoplayer.activity;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.google.android.material.tabs.TabLayout;
import com.lzw.cpvideoplayer.R;
import com.lzw.cpvideoplayer.data.TimeLine;
import com.lzw.cpvideoplayer.data.TitleData;
import com.lzw.cpvideoplayer.fragment.CatalogueFragment;
import com.lzw.cpvideoplayer.fragment.DetailsFragment;
import com.lzw.cpvideoplayer.data.cHeadData;
import com.lzw.cpvideoplayer.mvp.model.LoadHttpData;
import com.lzw.cpvideoplayer.adapter.MyPagerAdapter;
import com.lzw.cpvideoplayer.mvp.presenter.VideoPresenter;
import com.lzw.cpvideoplayer.mvp.view.BaseActivity;
import com.lzw.cpvideoplayer.mvp.view.IBaseView;
import com.lzw.cpvideoplayer.mvp.view.LoadDiaLog;
import com.lzw.cpvideoplayer.ulit.MyHolder;
import com.lzw.cpvideoplayer.ulit.Ulit;

import java.util.ArrayList;
import java.util.List;

public  class ContentActivity extends BaseActivity<IBaseView, VideoPresenter> implements View.OnClickListener,IBaseView<cHeadData> {

    /**
     * 视频播放页面 详情页
     * @param savedInstanceState
     */
    private boolean isStop;//视频是否暂停
    private TextView timeLine;//进度条时间
    private TextView timeLineMax;//进度条总时间
    private static final String TAG = "ContentActivity";
    private ImageButton mPlayBtn;//播放按钮
    boolean fullscreen = false;//是否处于全屏
    //    private SurfaceView mSfViwe;//用于视频显示
    private String cxkUrl = "https://vd2.bdstatic.com/mda-nitgwwga4f1siiqk/sc/cae_h264/1664366381350926546/mda-nitgwwga4f1siiqk.mp4?v_from_s=hkapp-haokan-hna&auth_key=1664643054-0-0-9478f8c16da28c1c0f1f3cd04c51f57c&bcevod_channel=searchbox_feed&cd=0&pd=1&pt=3&logid=1254197665&vid=12790229006915392210&abtest=104859_2&klogid=1254197665";
    private boolean isPlay = true;//是否还没播放完毕
    private VideoView mVdPlay;//用于视频播放
    private MyHolder holder ;
    private SeekBar mSeek;//进度条
    private ImageButton mFull;//播放按钮
    private int inPar = 0;//保存当前进度
    private ImageView mExit_img;//退出按钮
    private TextView mTextTitle;//视频标题
    private boolean isGone = true;
    private TabLayout mTab;//导航栏
    private ViewPager vp_list;
    private int old_position;//判断视频是否停止
    public static List<TitleData> searchdata;//视频的详细信息
    public static int position;//哪个视频
    private  int currpos;//视频当前进度
    private boolean isPlaying = true;//是否还没退出

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        initView();

    }

    @Override
    public VideoPresenter createPresenter() {
        return new VideoPresenter();
    }


    @Override
    public void ShowViewData(cHeadData data) {//显示View
    //设置视频地址
        mVdPlay.setVideoURI(Uri.parse(data.getData().getChapterList()[0].getChapterPath()));
    //
        mTextTitle.setText(data.getData().getTitle()+"\t"+data.getData().getChapterList()[0].getTitle());

        List<Fragment> list = new ArrayList<>();
        list.add(new DetailsFragment(searchdata,position));
        list.add(new CatalogueFragment(data,mVdPlay,mTextTitle));
        vp_list.setAdapter(new MyPagerAdapter(getSupportFragmentManager(),list));
        mTab.setupWithViewPager(vp_list);
        mTab.getTabAt(0).setText("详情");
        mTab.getTabAt(1).setText("目录");
//        mTab.setTabMode(TabLayout.MODE_SCROLLABLE);

    }


    //初始化控件
    private void initView() {
        vp_list = findViewById(R.id.vp_list);//
        mTab = findViewById(R.id.tab_list);

        timeLine = findViewById(R.id.times);
        timeLineMax = findViewById(R.id.timemax);
//        Toast.makeText(getApplicationContext(),"请等待视频加载",Toast.LENGTH_SHORT).show();
        mPlayBtn = findViewById(R.id.main_play_btn);//播放
        mVdPlay = findViewById(R.id.vd_view);//播放视图
        mFull = findViewById(R.id.vd_full);//放大按钮
        mSeek = findViewById(R.id.seek_main);//进度条
        holder = new MyHolder(mSeek,mVdPlay,timeLine,timeLineMax);//进度条控制器
        mExit_img = findViewById(R.id.exit_video);//退出播放页面
        mTextTitle  = findViewById(R.id.video_title);
        LoadDiaLog.getInstance(ContentActivity.this).show();//显示加载条

        presenter.fatch(ContentActivity.this,Ulit.CHAPTER_URL+getIntent().getStringExtra("videoId"));
        mExit_img.setOnClickListener(this);

        mVdPlay.setOnClickListener(new View.OnClickListener() {
            //播放按钮隐藏和显示
            @Override
            public void onClick(View v) {

                if(isGone){
                    mExit_img.setVisibility(View.GONE);//隐藏
                    mTextTitle.setVisibility(View.GONE);
                    mPlayBtn.setVisibility(View.GONE);
                    mSeek.setVisibility(View.GONE);
                    mFull.setVisibility(View.GONE);
                    timeLine.setVisibility(View.GONE);
                    timeLineMax.setVisibility(View.GONE);
                    isGone = false;
                }else {
                    mExit_img.setVisibility(View.VISIBLE);//显示
                    mTextTitle.setVisibility(View.VISIBLE);
                    mPlayBtn.setVisibility(View.VISIBLE);
                    mSeek.setVisibility(View.VISIBLE);
                    mFull.setVisibility(View.VISIBLE);
                    timeLine.setVisibility(View.VISIBLE);
                    timeLineMax.setVisibility(View.VISIBLE);
                    isGone = true;
                }

            }
        });
        mVdPlay.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mPlayBtn.setOnClickListener(ContentActivity.this);
                mFull.setOnClickListener(ContentActivity.this);
                //缓存完毕时
                LoadDiaLog.getInstance(ContentActivity.this).onLoadDismiss();
                PlayVideo();
              //  Log.e(TAG, "onPrepared: 加载完毕" );
                Toast.makeText(getApplicationContext(),"加载完毕",Toast.LENGTH_SHORT).show();
                SeekRun();
            }
        });
        mVdPlay.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                isPlay = false;
                mPlayBtn.setBackgroundResource(cn.jzvd.R.drawable.jz_play_normal);
                Log.e(TAG, "onCompletion:视频播放完毕 " );
            }
        });
        mSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            // 进度条准备完毕
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//                Log.e(TAG, "运行");

            }
            //进度条开始
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.e(TAG, "拖动");
            }
            //进度条停止
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int s = mSeek.getProgress();
                mVdPlay.seekTo(s);
                //  Log.e(TAG, "onStopTrackingTouch: "+s);
            }
        });
    }

    private void SeekRun() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isPlaying){

                    try {
                        Thread.sleep(800);//每隔1秒刷新进度条
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(!isPlaying){
                        return;
                    }
                   // Log.e(TAG, "run: "+old_position+"---"+currpos );
                    old_position = mVdPlay.getCurrentPosition();
                    Log.e(TAG, "loadRun: load..."+isStop+"-"+isPlay);
                if(!isStop&&isPlay){
                    if(currpos == old_position){
                        Log.e(TAG, "run: load..." );
                        Message msg = new Message();
                        msg.what = 2;
                        msg.obj = ContentActivity.this;
                        holder.sendMessage(msg);
                    }else {
                        Message msg = new Message();
                        msg.what = 3;
                        msg.obj = ContentActivity.this;
                        holder.sendMessage(msg);
                    }
                }else {
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = ContentActivity.this;
                    holder.sendMessage(msg);
                }

                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {

                TimeLine time = new TimeLine();
                while (isPlaying){
                    Log.e(TAG, "run2: " );
                    try {
                        Thread.sleep(500);//每隔0.5秒刷新进度条
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    currpos = mVdPlay.getCurrentPosition();
                    int currMax = mVdPlay.getDuration();
                    Message msg = new Message();
                    msg.what = 1;
                    msg.arg1 = currpos;
                    msg.arg2 = currMax;//视频长度

                    time.setS(currpos/1000%60);
                    time.setM(currpos/1000/60%60);
                    time.setH(currpos/1000/60/60%60);
                    time.setMaxTime(currMax);
                    msg.obj = time;

                    if(currpos!=-1&&currMax!=-1){
                        holder.sendMessage(msg);
                    }
//
//                    if(mSeek.getProgress() == mSeek.getMax()){
//                        Log.e(TAG, "run: "+"return" );
//                        return;//结束循环
//                    }
                }
            }
        }).start();
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.main_play_btn:
                if(mVdPlay.isPlaying()){
                   PauseVideo();

                }else{
                   PlayVideo();

//                    Log.e(TAG, "onClick: start" );
                }
                break;
            case R.id.vd_full:
                if(fullscreen) {//缩小
                    onZoom();
                }else{//全屏
                    onFull();
                }
                break;
            case R.id.exit_video:
                Log.e(TAG, "onClick:Exit " );
                //退出当前页面
                if(!fullscreen){
                    Log.e(TAG, "onKeyDown:点击了返回按钮 " );
                    finish();
                }else {
                    Log.e(TAG, "onKeyDown:点击了返回按钮 " );
                    onZoom();
                }
                break;
        }
    }



    //缩小播放
    public void onZoom(){
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        if(getSupportActionBar() != null){
            getSupportActionBar().show();
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mVdPlay.getLayoutParams();
        params.width = params.MATCH_PARENT;
        params.height = (int) ( 200 * getApplicationContext().getResources().getDisplayMetrics().density);
        mVdPlay.setLayoutParams(params);
        fullscreen = false;
        mFull.setBackgroundResource(R.drawable.full);
        Log.e(TAG, "onClick: "+params.width+"-"+params.height);
    }
    public void onFull(){
        //全屏播放
        mFull.setBackgroundResource(R.drawable.zoom);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
                |View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                |View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mVdPlay.getLayoutParams();
        params.width = params.MATCH_PARENT;
        params.height = params.MATCH_PARENT;
        mVdPlay.setLayoutParams(params);
        fullscreen = true;
    }

    public void PlayVideo(){//播放视频
        isStop = false;
        mPlayBtn.setAlpha(1f);
        mSeek.setMax(mVdPlay.getDuration());
        mPlayBtn.setBackgroundResource(cn.jzvd.R.drawable.jz_pause_pressed);
        mVdPlay.start();
    }
    public void PauseVideo(){//暂停视频
        isStop = true;
        mPlayBtn.setBackgroundResource(cn.jzvd.R.drawable.jz_play_normal);
        mPlayBtn.setAlpha(0.5f);
//                    Log.e(TAG, "onClick: pause" );
        mVdPlay.pause();
    }

    //物理返回按钮禁用

    public boolean onKeyDown(int keyCode, KeyEvent event) {//重写物理返回按钮
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //退出当前页面
            if(!fullscreen){
                finish();
            }else {
                onZoom();

            }
            LoadDiaLog.getInstance(ContentActivity.this).onLoadDismiss();//关闭加载动画
            Log.e(TAG, "onKeyDown:点击了物理返回键 " );
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ");
        isPlaying = false;
        LoadHttpData.isLoadData = true;
        LoadDiaLog.getInstance(ContentActivity.this).onLoadDismiss();
    }

    @Override
    protected void onStop() {
        super.onStop();
        inPar = mSeek.getProgress();//获取当前进度
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVdPlay.pause();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //返回app继续播放
        Log.e(TAG, "onStart: ");
        mVdPlay.seekTo(inPar);
        mPlayBtn.setBackgroundResource(cn.jzvd.R.drawable.jz_play_normal);
    }
}